package cn.bonoon.kernel.web.views;
//
//package cn.bonoon.kernel.support.views;
//
//import java.io.Reader;
//import java.io.StringReader;
//import java.io.StringWriter;
//import java.io.Writer;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//import org.apache.velocity.Template;
//import org.apache.velocity.VelocityContext;
//import org.apache.velocity.app.VelocityEngine;
//import org.apache.velocity.context.Context;
//import org.apache.velocity.exception.MethodInvocationException;
//import org.apache.velocity.tools.view.context.ChainedContext;
//import org.springframework.beans.BeansException;
//import org.springframework.beans.factory.BeanFactoryUtils;
//import org.springframework.beans.factory.InitializingBean;
//import org.springframework.beans.factory.NoSuchBeanDefinitionException;
//import org.springframework.context.ApplicationContextException;
//import org.springframework.web.servlet.view.document.AbstractPdfView;
//import org.springframework.web.servlet.view.velocity.VelocityConfig;
//import org.springframework.web.util.NestedServletException;
////
////import com.lowagie.text.Document;
////import com.lowagie.text.html.HtmlParser;
////import com.lowagie.text.pdf.PdfWriter;
//
///**
// * <pre>
// * 使用velocity模板引擎解析,并生成pdf的视图类
// * </pre>
// * 
// * @author jackson
// * 
// */
//@SuppressWarnings("deprecation")
//public class ExportPdfView extends AbstractPdfView implements InitializingBean{
//
//	public static final String DEFAULT_LAYOUT_URL = "layout-pdf.vm";
//	public static final String DEFAULT_LAYOUT_KEY = "layout";
//	public static final String DEFAULT_SCREEN_CONTENT_KEY = "screen_content";
//	
//	private String layoutUrl = DEFAULT_LAYOUT_URL;
//	private String layoutKey = DEFAULT_LAYOUT_KEY;
//	private String screenContentKey = DEFAULT_SCREEN_CONTENT_KEY;
//
//	private String encoding;
//	private boolean cacheTemplate = false;
//	private VelocityEngine velocityEngine;
//	private PdfEntry pdfEntry;
//	private Map<String, Template> cache;
//	private final List<String> viewNames = new ArrayList<String>();
//
//	public final void add(String viewName) {
//		viewNames.add(viewName);
//	}
//	
//	public final void add(String... viewNames){
//		for(int i = 0; i < viewNames.length; i++){
//			this.viewNames.add(viewNames[i]);
//		}
//	}
//
//	@Override
//	protected void buildPdfMetadata(Map<String, Object> model,
//			Document document, HttpServletRequest request) {
//		super.buildPdfMetadata(model, document, request);
//		if (null != pdfEntry) {
//			pdfEntry.addTo(document);
//		}
//	}
//
//	@Override
//	protected void buildPdfDocument(Map<String, Object> model,
//			Document document, PdfWriter writer, HttpServletRequest request,
//			HttpServletResponse response) throws Exception {
//		Context velocityContext = createVelocityContext(model, request,
//				response);
//		for (int i = 0, len = viewNames.size(); i < len; i++) {
//			Writer sw = new StringWriter();
//			doRender(velocityContext, sw, viewNames.get(i));
//			Reader r = new StringReader(sw.toString());
//			
//			if(i > 0){
//				document.newPage();
//			}
//			HtmlParser.parse(document, r);
//		}
//	}
//
////	private final Font getChineseFont(float size) {
////		Font cf = null;
////		try {
////			BaseFont bfChinese = BaseFont.createFont("STSong-Light",
////					"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
////			cf = new Font(bfChinese, size, Font.NORMAL);
////		} catch (DocumentException de) {
////			this.logger.error("pdf异常:", de);
////		} catch (IOException ioe) {
////			this.logger.error("IO异常:", ioe);
////		}
////		return cf;
////	}
//
//	protected void doRender(Context context, Writer writer, String vName)
//			throws Exception {
//		renderScreenContent(context, vName);
//
//		// Velocity context now includes any mappings that were defined
//		// (via #set) in screen content template.
//		// The screen template can overrule the layout by doing
//		// #set( $layout = "MyLayout.vm" )
//		String layoutUrlToUse = (String) context.get(this.layoutKey);
//		if (layoutUrlToUse == null) {
//			// No explicit layout URL given -> use default layout of this view.
//			layoutUrlToUse = this.layoutUrl;
//		}
//
//		mergeTemplate(getTemplate(layoutUrlToUse), context, writer);
//	}
//
//	private void renderScreenContent(Context velocityContext, String vName)
//			throws Exception {
//		if (logger.isDebugEnabled()) {
//			logger.debug("Rendering screen content template [" + vName + "]");
//		}
//
//		StringWriter sw = new StringWriter();
//		Template screenContentTemplate;
//		if (cacheTemplate) {
//			if (null == cache)
//				cache = new HashMap<String, Template>();
//			if(cache.containsKey(vName)){
//				screenContentTemplate = cache.get(vName);
//			}else{
//				screenContentTemplate = getTemplate(vName);
//				cache.put(vName, screenContentTemplate);
//			}
//		}else{
//			screenContentTemplate = getTemplate(vName);
//		}
//
//		screenContentTemplate.merge(velocityContext, sw);
//
//		// Put rendered content into Velocity context.
//		velocityContext.put(this.screenContentKey, sw.toString());
//	}
//
//	protected void mergeTemplate(Template template, Context context,
//			Writer writer) throws Exception {
//
//		try {
//			template.merge(context, writer);
//		} catch (MethodInvocationException ex) {
//			Throwable cause = ex.getWrappedThrowable();
//			throw new NestedServletException(
//					"Method invocation failed during rendering of Velocity view with name '"
//							+ getBeanName() + "': " + ex.getMessage()
//							+ "; reference [" + ex.getReferenceName()
//							+ "], method '" + ex.getMethodName() + "'",
//					cause == null ? ex : cause);
//		}
//	}
//
//	protected Context createVelocityContext(Map<String, Object> model,
//			HttpServletRequest request, HttpServletResponse response)
//			throws Exception {
//		ChainedContext velocityContext = new ChainedContext(
//				new VelocityContext(model), getVelocityEngine(), request,
//				response, getServletContext());
//		return velocityContext;
//	}
//
//	public final String getScreenContentKey() {
//		return screenContentKey;
//	}
//
//	public final void setScreenContentKey(String screenContentKey) {
//		this.screenContentKey = screenContentKey;
//	}
//
//	public final String getLayoutUrl() {
//		return layoutUrl;
//	}
//
//	public final void setLayoutUrl(String layoutUrl) {
//		this.layoutUrl = layoutUrl;
//	}
//
//	public final String getLayoutKey() {
//		return layoutKey;
//	}
//
//	public final void setLayoutKey(String layoutKey) {
//		this.layoutKey = layoutKey;
//	}
//
//	public final PdfEntry getPdfEntry() {
//		return pdfEntry;
//	}
//
//	public final void setPdfEntry(PdfEntry pdfEntry) {
//		this.pdfEntry = pdfEntry;
//	}
//
//	public final String getEncoding() {
//		return encoding;
//	}
//
//	public final void setEncoding(String encoding) {
//		this.encoding = encoding;
//	}
//
//	public final boolean isCacheTemplate() {
//		return cacheTemplate;
//	}
//
//	public final void setCacheTemplate(boolean cacheTemplate) {
//		this.cacheTemplate = cacheTemplate;
//	}
//
//	public final VelocityEngine getVelocityEngine() {
//		return velocityEngine;
//	}
//
//	public final void setVelocityEngine(VelocityEngine velocityEngine) {
//		this.velocityEngine = velocityEngine;
//	}
//
//	@Override
//	protected void initApplicationContext() throws BeansException {
//		super.initApplicationContext();
//
//		if (getVelocityEngine() == null) {
//			// No explicit VelocityEngine: try to autodetect one.
//			setVelocityEngine(autodetectVelocityEngine());
//		}
//	}
//
//	protected VelocityEngine autodetectVelocityEngine() throws BeansException {
//		try {
//			VelocityConfig velocityConfig = BeanFactoryUtils
//					.beanOfTypeIncludingAncestors(getApplicationContext(),
//							VelocityConfig.class, true, false);
//			return velocityConfig.getVelocityEngine();
//		} catch (NoSuchBeanDefinitionException ex) {
//			throw new ApplicationContextException(
//					"Must define a single VelocityConfig bean in this web application context "
//							+ "(may be inherited): VelocityConfigurer is the usual implementation. "
//							+ "This bean may be given any name.", ex);
//		}
//	}
//
//	protected Template getTemplate(String name) throws Exception {
//		return (getEncoding() != null ? getVelocityEngine().getTemplate(name,
//				getEncoding()) : getVelocityEngine().getTemplate(name));
//	}
//
//	@Override
//	public void afterPropertiesSet() throws Exception {
//		if(viewNames.isEmpty())
//			throw new IllegalArgumentException("Property 'viewNames' is empty");
//	}
//}